package tmt.usercenter.web.service;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tmt.usercenter.web.domain.TmtUser;
import tmt.usercenter.web.domain.UserBinding;
import tmt.usercenter.web.domain.enums.UserBindingType;
import tmt.usercenter.web.repository.IUserBindingRepo;

import java.util.ArrayList;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserBindingService extends TmtBaseService<UserBinding, Long> {

    @Getter
    private IUserBindingRepo iUserBindingRepo;

    private PasswordEncoder passwordEncoder;

    private TmtUserService userService;

    @Autowired
    public UserBindingService(IUserBindingRepo iUserBindingRepo, TmtUserService userService, PasswordEncoder passwordEncoder) {
        super(iUserBindingRepo, new ArrayList<>());
        this.iUserBindingRepo = iUserBindingRepo;
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @Transactional(readOnly = true)
    public UserBinding findByOpenIdAndBindingType(String openId, UserBindingType bindingType) {
        return iUserBindingRepo.findByOpenIdAndBindingType(openId, bindingType);
    }

    /**
     * 更新用户账号绑定的微信号
     * @param bindingInfo
     * @throws Exception
     */
    public void updateOpenId(UserBinding bindingInfo) throws Exception {
        TmtUser user = bindingInfo != null ? bindingInfo.getUser() : null;

        if (user == null)
            throw new Exception("用户不存在");

        if (StringUtils.isEmpty(bindingInfo.getOpenId()))
            throw new Exception("openId参数无效");

        TmtUser curUser = userService.findByUsername(user.getUsername());
        if (curUser == null || !passwordEncoder.matches(user.getPassword(), curUser.getPassword())) {
            throw new Exception("账号或密码错误");
        }

        UserBinding userBinding = iUserBindingRepo.findByUserIdAndBindingType(curUser.getId(), bindingInfo.getBindingType());
        if (userBinding == null){
            userBinding = new UserBinding();
            userBinding.setBindingType(bindingInfo.getBindingType());
            userBinding.setUser(curUser);
        }
        userBinding.setOpenId(bindingInfo.getOpenId());
        iUserBindingRepo.save(userBinding);
    }
}
